/*
 * @Author: 史许荣
 * @Date: 2022-08-01 10:57:57
 * @LastEditors: 史许荣
 * @LastEditTime: 2022-08-04 15:14:19
 * @Description: file content
 * @FilePath: \react-three-fiber-new\src\Frames.js
 */
import * as THREE from 'three'
import {  useEffect, useRef } from 'react'
import {  useFrame } from '@react-three/fiber'
import Model from './Model'
const urlList = [
    { name:'3D打印', position: [15, 20, -30],position2:[-15,20,-30]},
    { name:'自动包装发货', position: [-30, 20, -15],position2:[-30,20,15]},
    { name:'CNC机器人', position: [-15, 20, 30],position2:[15,20,30]},
    { name:'热成型', position: [30, 20, 15],position2:[30,20,-15]},
  ]
  
export default function Frames({ id,setId,p = new THREE.Vector3() }) {
    const ref = useRef()
    const key = useRef(0)
    const animatedOpen=useRef(false)
    useEffect(() => {
        if(key.current!=(sessionStorage.getItem("threeModelKey")||0)){
            key.current=sessionStorage.getItem("threeModelKey")||0;
            
            setId(key.current)
            
            key.current=sessionStorage.getItem("threeModelKey")||0;
            p.set(...urlList[key.current%4].position)
        }else{
            p.set(...urlList[key.current%4].position)
        }
    })
    useFrame((state, dt) => {
        let p1=urlList[key.current%4].position;
        let p2=urlList[key.current%4].position2;
        if(key.current!=(sessionStorage.getItem("threeModelKey")||0)){
            key.current=sessionStorage.getItem("threeModelKey")||0;
            p.set(...p1)
            setId(key.current)
        }
        else if(state.camera.position.x.toFixed(0)==p1[0]&&state.camera.position.z.toFixed(0)==p1[2]&&!animatedOpen.current){
            p.set(...p2)
            animatedOpen.current=true;
            
        }
        else if(state.camera.position.x.toFixed(0)==p2[0]&&state.camera.position.z.toFixed(0)==p2[2]&&animatedOpen.current){
            animatedOpen.current=false;
            sessionStorage.setItem("threeModelKey",(1+Number(key.current))%5)
        }
        
        if(animatedOpen.current){
            state.camera.position.lerp(p, 0.005)
        }else{
            state.camera.position.lerp(p, 0.025)}
    })


    return (
      <group
        ref={ref}>
        <Model url={"/gltf/x1.glb"} opacity={0.3} />
        <Model url={"/gltf/x2.glb"} opacity={0.3} />
        <Model url={"/gltf/x3.glb"} opacity={0.5} />
  
  
        <Model url={"/gltf/line1.glb"} opacity={1} />
        <Model url={"/gltf/line2.glb"} opacity={1} />
        <Model url={"/gltf/line3.glb"} opacity={1} />
      </group>
    )
  }
  